<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="`${isUpdate ? '编辑' : '添加'}公司`"
    width="60%"
    centered
    @ok="handleSubmit"
    @visible-change="visibleChange"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { formSchema } from './data'
import { useMessage } from '@/hooks/web/useMessage'

const isUpdate = ref(true)
const profile = ref()
const emit = defineEmits(['success', 'register'])
const { createMessage } = useMessage()
const { createErrorModal } = useMessage()
const modalTitle = ref('')
const userState = ref({ value: null, fetching: null, data: null })

const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  labelAlign: 'right',
  actionColOptions: {
    span: 24,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  profile.value = data.record

  if (unref(isUpdate)) {
    await setFieldsValue({
      ...data.record,
    });
  }
})

const handleSubmit = async () => {
  try {
    const values = await validate()

    let data = null
    if (!data.code) {
      createMessage.success(`设置成功！`)
      emit('success', {})
      closeModal()
    } else {
      createMessage.warn(`设置失败！`)
    }
  } catch (e) {
    //console.log(e)
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

const visibleChange = async (visible: any) => {}

const filterOptions = (input, option) => {
  if (input.length >= 2) return option.label.indexOf(input) !== -1
}

const searchUserHandle = async (keyword) => {
  if (11 != keyword.length) return false;
  const { result: { list = [] } } = await getUserOptions({ keyword });
  if (!Array.isArray(list) || 0 === list.length){
    createMessage.warn(`用户不存在！`);
    return false;
  }
  userState.value.data = list as any;
}
</script>

<style lang="less" scoped>
:deep(.ant-upload-select-picture-card) {
  width: 60px !important;
  height: 106px !important;
}
</style>
